package cn.com.eado.crm.app.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.List;

public class GsonUtil {

    public static <T> List<T> getListFromAssetsJson(String fileName, Context context, Type type){
        String s = getAssetsJson(fileName, context);
        String s1 = s.substring(s.indexOf("["), s.lastIndexOf("]")+1).trim();
//        Log.e("tag", "s1="+s1);
//        Type type = new TypeToken<List<T>>(){}.getType();
        return new Gson().<List<T>>fromJson(s1, type);
    }

    public static String getAssetsJson(String fileName, Context context){
        StringBuffer sb = new StringBuffer();
        AssetManager manager = context.getAssets();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(manager.open(fileName)));
            String line;
            while ((line = br.readLine()) != null){
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    public static String getString(Context context, String assetsName){
        String s = getAssetsJson(assetsName, context);
        return s.substring(s.indexOf("["), s.lastIndexOf("]")+1).trim();
    }

    public static <T> List<T> getList(String s, Type type){
        return new Gson().fromJson(s, type);
    }



}
